package com.xiaobai.mall.item.service;

import com.github.pagehelper.PageHelper;
import com.xiaobai.mall.item.dao.ItemMapper;
import com.xiaobai.mall.item.domain.Item;
import com.xiaobai.mall.item.dto.ItemDTO;
import com.xiaobai.mall.item.interfaces.IItemService;
import com.xiaobai.mall.item.param.ItemQueryParam;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class ItemService implements IItemService {

    @Resource
    private ItemMapper itemMapper;


    @Override
    public List<Item> queryList() {
        return itemMapper.queryList(new ItemQueryParam());
    }

    @Override
    public List<Item> queryListByParam(ItemQueryParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        itemMapper.queryList(param);
        return itemMapper.queryList(param);
    }

    @Override
    public Item queryItemByOuterId(String outerId) {
        ItemQueryParam itemQueryParam = new ItemQueryParam();
        itemQueryParam.setOuterId(outerId);
        return Optional.ofNullable(queryListByParam(itemQueryParam)).filter(list -> list.size() > 0).map(list -> list.get(0)).orElse(null);
    }

    @Override
    public Item queryItemById(Long id) {
        return itemMapper.queryById(id);
    }

    @Override
    public void deleteItem(Long id) {
        itemMapper.deleteItem(id);
    }

    @Override
    public Item createItem(ItemDTO itemDTO) {
        Assert.isNull(queryItemByOuterId(itemDTO.getOuterId()), String.format("存在商家编码为[%s]的商品", itemDTO.getOuterId()));
        Item target = new Item();
        BeanUtils.copyProperties(itemDTO, target);
        Boolean result = itemMapper.saveItem(target);
        return target;
    }

    @Override
    public Item updateItem(ItemDTO itemDTO) {
        return null;
    }

    @Override
    public void updatePublishStatus(Long id, Integer publishStatus) {

    }
}
